<template>
  <div>
    <el-dialog title='创建任务'
      :visible.sync="visible"
      :close-on-click-modal="false"
      :append-to-body="true"
      width="800px">
      <el-form :model="form" ref="form" style="font-size:14px; line-height:36px; padding: 0 40px;">
        <el-row :gutter="20" v-if="taskType === 1">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-coin"></i>
              所属项目
              <span style="color:red;">*</span>
            </div>
          </el-col>
          <el-col :span="20">
            <el-select v-model="form.taskBelongId" placeholder="点击选择" style="width:calc(100% - 90px);"> 
              <el-option
                v-for="value in projectList"
                :key="value.id"
                :label="value.taskName"
                :value="value.id"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-else-if="taskType === 2 || taskType === 3 || taskType === 4">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-coin"></i>
              所属项目
            </div>
          </el-col>
          <el-col :span="20">{{subTaskInProject}}</el-col>
        </el-row>
        <el-row :gutter="20" v-else>
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-coin"></i>
              所属任务
              <span style="color:red;">*</span>
            </div>
          </el-col>
          <el-col :span="20">
            <el-select ref="taskBelongIdList" v-model="form.taskBelongId" placeholder="点击选择" style="width:calc(100% - 90px);"> 
              <el-option
                v-for="value in taskList"
                :key="value.id"
                :label="value.taskName"
                :value="value.id"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="position: relative;">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-document"></i>
              任务名称
              <span style="color:red;">*</span>
            </div>
          </el-col>
          <el-col :span="20">
            <el-input type="text" placeholder="必填项，限制字符30个" v-model="form.taskName" style="width:calc(100% - 90px);"></el-input>
            <div class="module-cover">
              <img :src="form.taskUrl? 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/task/'+form.taskUrl : 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/task/icon%20blue-1.png'"  style="width: 70px; height: 70px;display:block;border-radius: 5px;">
              <div class="click-block" @click="openCoverChange">更换图片</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-user"></i>
              负责人
              <span style="color:red;">*</span>
            </div>
          </el-col>
          <el-col :span="7" style="padding-top: 4px;">
            <div v-if="dingUserList.principal.id.length === 0" @click="selectDingUsers('principal')" class="select-btn"><span><i class="el-icon-plus"></i></span>添加</div>
            <div class="select-btn" v-for="(item, index) in dingUserList.principal.id" :key="item.index">
              <span><img :src="dingUserList.principal.img[index]" /></span>{{dingUserList.principal.name[index]}}
              <div class="del" @click="delMember('principal', index)">移除</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-user"></i>
              确认人
              <span style="color:red;">*</span>
            </div>
          </el-col>
          <el-col :span="7" style="padding-top: 4px;">
            <div v-if="dingUserList.confirm.id.length === 0" @click="selectDingUsers('confirm')" class="select-btn"><span><i class="el-icon-plus"></i></span>添加</div>
            <div class="select-btn" v-for="(item, index) in dingUserList.confirm.id" :key="item.index">
              <span><img :src="dingUserList.confirm.img[index]" /></span>{{dingUserList.confirm.name[index]}}
              <div class="del" @click="delMember('confirm', index)">移除</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-date"></i>
              起止时间
              <span style="color:red;">*</span>
            </div>
          </el-col>
          <el-date-picker
            v-model="taskTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changePlanTime"
            style="width: 474px; margin-left: 10px;"
          ></el-date-picker>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-time"></i>
              计划工期
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              {{planTime}}
              天
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-data-line"></i>
              任务绩效
              <span style="color:red;">*</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <el-input v-model="form.taskPerformanceAppraisal"  style="width : 80px;"></el-input>
              分
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-bottom: 5px;">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-edit-outline"></i>
              任务描述
            </div>
          </el-col>
          <el-col :span="20">
            <div class="grid-content bg-purple" style="padding-top: 10px;position:relative;">
              <el-input resize="none" style="width: 474px;margin-bottom: 5px;" type="textarea" :rows="4" v-model="form.taskInfo"></el-input>
              <input ref="uploadInput" style="display:none;" type="file" @change="uploadFile($event)" multiple>
              <span class="addfilebtn" @click="$refs.uploadInput.click()"><i class="el-icon-paperclip" style=""></i>添加附件</span>
              <div class="fileitem" v-for="(file, idx) in form.taskAttachment" :key="idx">
                <img style="width:16px;height:16px;position:relative;top:-2px;margin-right:2px;" :src="getPic(file.name)" alt="">{{file.name}}
                <span class="uploadtip" v-if="file.url" @click="delFile(idx)"><i class="el-icon-delete"></i></span>
                <span class="uploadtip" style="color: red;cursor:none;" v-if="!file.url">上传中<i class="el-icon-loading"></i></span>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <i class="el-icon-star-off"></i>
              关注人
            </div>
          </el-col>
          <el-col :span="20" style="padding-top: 4px;">
            <div @click="selectDingUsers('cc', 300)" class="select-btn"><span><i class="el-icon-plus"></i></span>添加</div>
            <div class="select-btn" v-for="(item, index) in dingUserList.cc.id" :key="item.index" style="margin-bottom: 10px;">
              <span><img :src="dingUserList.cc.img[index]" /></span>{{dingUserList.cc.name[index]}}
              <div class="del" @click="delMember('cc', index)">移除</div>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="small">创 建</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择图片" :visible.sync="coverDialog"  width="440px" :append-to-body="true">
      <div class="cover-wrapper">
        <div v-for="cover in 15" :key="cover">
          <img :src="'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/task/icon%20blue-' + cover + '.png'" style="width: 70px; height: 70px;display:block;border-radius: 5px;">
          <div class="click-block" @click="selectCover('icon%20blue-' + cover + '.png')">选择</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dingMixin from "@/mixins/ding";
import formUtil from "@/utils/formUtil";
import {dateUtil} from '@/utils/dateUtil'

export default {
  data() {
    return {
      headers: {
        token: this.$cookie.get("token")
      },
      visible: false,
      subTaskInProject: "",
      taskType: 1,  //1-创建任务  2-在项目中创建任务  3-创建子任务  4-复制任务  5-复制子任务
      projectList: [],
      taskList: [],
      dingUserList: {
        principal: { id: [], img: [], name: [] },
        confirm: { id: [], img: [], name: [] },
        cc: { id: [], img: [], name: [] }
      },
      planTime: 0,
      taskTime: [],
      form: {
        taskName: "",
        taskInfo: "",
        taskBelongId: "",
        taskBelongName: "",
        taskPrincipalId: "",
        principalAvatar: "",
        taskPrincipalName: "",
        taskConfirmId: "",
        confirmAvatar: "",
        taskConfirmName: "",
        taskStartTime: "",
        taskEndTime: "",
        taskCcId: "",
        ccAvatar: "",
        taskCcName: "",
        taskPerformanceAppraisal: 0,
        taskStatus: 0,
        taskAttachment: [],
        taskDatatype: 0
      },
      coverDialog: false
    };
  },
  mixins: [dingMixin],
  methods: {
    init(data) {
      formUtil.resetData(this.form);
      formUtil.resetData(this.dingUserList);
      if(data.copyTask) {
        this.form = data.data
        if(this.form.taskDatatype === '2') {
          this.taskType = 4;
          this.subTaskInProject = this.form.taskBelongName;
        } else if (this.form.taskDatatype === '3') {
          this.taskType = 5;
          this.getTaskListUnderProject(this.form.taskBelongId);
          this.form.taskBelongId = '';
          this.form.taskBelongName = '';
        }
        this.planTime = parseInt((new Date(this.form.taskEndTime) - new Date(this.form.taskStartTime)) / 1000 / 60 / 60 / 24) + 1;
        this.taskTime = [this.form.taskStartTime, this.form.taskEndTime];
        if (this.form.taskPrincipalId !== '') this.dingUserList.principal.id = this.form.taskPrincipalId.split(',');
        if (this.form.principalAvatar !== '') this.dingUserList.principal.img = this.form.principalAvatar.split(',');
        if (this.form.taskPrincipalName !== '') this.dingUserList.principal.name = this.form.taskPrincipalName.split(',');
        if (this.form.taskConfirmId !== '') this.dingUserList.confirm.id = this.form.taskConfirmId.split(',');
        if (this.form.confirmAvatar !== '') this.dingUserList.confirm.img = this.form.confirmAvatar.split(',');
        if (this.form.taskConfirmName !== '') this.dingUserList.confirm.name = this.form.taskConfirmName.split(',');
        if (this.form.taskCcId !== '')  this.dingUserList.cc.id = this.form.taskCcId.split(',');
        if (this.form.ccAvatar !== '')  this.dingUserList.cc.img = this.form.ccAvatar.split(',');
        if (this.form.taskCcName !== '')  this.dingUserList.cc.name = this.form.taskCcName.split(',');
      } else {
        this.taskTime = [];
        this.planTime = 0;
        this.form.taskPerformanceAppraisal = 0;
        this.form.taskUrl = 'icon%20blue-1.png';
        this.form.taskDatatype = data.taskDatatype;
        
        if (data.taskDatatype === 2) {
          if (data.id) {
            this.taskType = 2;
            this.form.taskBelongId = data.id;
            this.form.taskBelongName = data.taskName;
            this.subTaskInProject = data.taskName;
          } else {
            this.taskType = 1;
            this.getProjectList();
          }
        } else if (data.taskDatatype === 3) {
          this.taskType = 3;
          this.form.taskBelongId = data.id;
          this.form.taskBelongName = data.taskName;
          this.subTaskInProject = data.projectName + ' - ' + data.taskName;
        }
      }
      this.visible = true;
    },
    async getTaskListUnderProject(taskId) {
      let taskInfo = await this.$httpN.postB('division/task/taskInfo', {id:taskId})
      let list = await this.$httpN.postB('division/task/getUnCompleteTask', {id: taskInfo.taskBelongId})
      this.taskList = list.filter(item => {
        return item.taskDatatype === '2' && item.taskStatus === '1'
      })
    },
    //获取项目列表
    async getProjectList() {
      this.projectList = await this.$httpN.postB("division/task/getVisibleProjectList", {taskStatus: '1'});
    },
    changePlanTime(e) {
      if (e) {
        let startTime = e[0];
        let endTime = e[1];
        this.planTime = parseInt((endTime - startTime) / 1000 / 60 / 60 / 24) + 1;
        this.taskTime = [startTime, endTime];
        this.form.taskStartTime = startTime;
        this.form.taskEndTime = endTime;
      } else {
        this.planTime = 0;
        this.form.taskStartTime = "";
        this.form.taskEndTime = "";
      }
    },
    selectDingUsers(showName, number = 1) {
      this.complexPicker(number, [], this.dingUserList[showName].id).then(
        data => {
          this.dingUserList[showName].id = [];
          this.dingUserList[showName].img = [];
          this.dingUserList[showName].name = [];
          data.forEach((item, idx) => {
            this.dingUserList[showName].id.push(item.emplId);
            this.dingUserList[showName].img.push(item.avatar);
            this.dingUserList[showName].name.push(item.name);
          });
        }
      );
    },
    delMember(showName, index) {
      this.dingUserList[showName].id.splice(index,1);
      this.dingUserList[showName].img.splice(index,1);
      this.dingUserList[showName].name.splice(index,1);
    },
    async submitForm() {
      if(!this.form.taskBelongId) return this.$message.error(this.form.taskDatatype === 2 ? '请选择所属项目' : '请选择所属任务')
      if(!this.form.taskName) return this.$message.error('请输入任务名称')
      if(this.form.taskName.length > 30) return this.$message.error('任务名称不要超过30个字')
      if(this.form.taskAttachment.filter(item => !item.url).length > 0) return this.$message.error('附件正在上传，请稍候……');
      if(this.dingUserList.principal.id.length < 1) return this.$message.error('请选择任务负责人')
      if(this.dingUserList.confirm.id.length < 1) return this.$message.error('请选择任务确认人')
      if(!this.form.taskStartTime) return this.$message.error('请选择任务开始时间')
      if(!this.form.taskEndTime) return this.$message.error('请选择任务结束时间')
      if(isNaN(this.form.taskPerformanceAppraisal)) return this.$message.error('任务绩效为数字')
      if(this.form.taskPerformanceAppraisal < 0) return this.$message.error('任务绩效大于0')

      this.projectList.forEach(item => {
        if (item.id === this.form.taskBelongId) {
          this.form.taskBelongName = item.taskName;
          return false;
        }
      });
      if(this.taskType === 5) this.form.taskBelongName = this.$refs['taskBelongIdList'].selectedLabel;

      this.form.taskPrincipalId = this.dingUserList.principal.id.join(",");
      this.form.taskPrincipalName = this.dingUserList.principal.name.join(",");
      this.form.taskConfirmId = this.dingUserList.confirm.id.join(",");
      this.form.taskConfirmName = this.dingUserList.confirm.name.join(",");
      this.form.taskCcId = this.dingUserList.cc.id.join(",");
      this.form.taskCcName = this.dingUserList.cc.name.join(",");
      this.form.taskManageId = this.userInfo.dingId;
      this.form.taskManageName = this.userInfo.realName;

      if (!this.form.taskStatus) this.form.taskStatus = 1;
      if (!(await this.$httpN.postB("division/task/projectOrTaskSave", this.form))) return;
      this.visible = false;
      formUtil.submitSuccess("保存成功");
      this.$emit('refresh');
    },
    async uploadFile(e) {
      var files = e.target.files;
      var $this = this;
      Object.keys(files).forEach(function(key){
        var file = files[key];
        if(file.size / 1024 / 1024 > 20) return $this.mobileAlert('上传单个文件大小不能超过20MB!请压缩文件')
        var formData = new FormData();
        formData.append("file", file);
        formData.append("name", 'file');
        let newfile = {
          name: file.name,
          url: '',
          size: file.size,
          uploader: $this.userInfo.realName,
          time: dateUtil.thisDay()
        }
        $this.form.taskAttachment.push(newfile)
        $this.$httpN.upload('fileUpload', formData).then(res => {
          if(res.data.code === 0) {
            newfile.url = res.data.url;;
          }else if(res.data.code === 500) {
            $this.form.taskAttachment.pop();
          }
        })
      })
      e.target.value = '';
    },
    delFile(idx){
      this.form.taskAttachment.splice(idx, 1)
    },
    openCoverChange() {
      this.coverDialog = true;
    },
    selectCover(img) {
      this.coverDialog = false;
      this.form.taskUrl = img
    },
    getPic(filename) {
      if(filename) {
        if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438103037435905.png'
        }else if(/\.(txt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438530785140737.png'
        }else if(/\.(xls|xlsx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438725690253314.png'
        }else if(/\.(doc|docx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439195636850689.png'
        }else if(/\.(psd)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439984203751426.png'
        }else if(/\.(pdf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440139145535490.png'
        }else if(/\.(ppt|pptx|dps|dpt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440657859305473.png'
        }else if(/\.(rar|zip|arj|gz)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442063039193090.png'
        }else if(/\.(html|htm)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442135319633921.png'
        }else if(/\.(dwg|bak|dwt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276441741667459074.png'
        }else if(/\.(wav|aif|au|mp3|ram|wma|mmf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442006684524546.png'
        }else if(/\.(avi|mov|rmvb|rm|flv|mp4)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442233483124737.png'
        }else{
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
        }
      }else {
        return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
      }
    }
  }
};
</script>

<style lang='scss' scoped>
.select-btn{
  float:left;
  font-weight: normal;
  margin-right: 5px;
  width: 80px;
  height: 28px;
  border-radius: 30px;
  background: #FAFAFA;
  border: 1px solid #ECECEC;
  position: relative;
  padding-left: 21px;
  line-height: 28px;
  color: #7982A7;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
  span{
    position: absolute;
    top: 1px;
    left: 1px;
    display:block;
    height: 24px;
    width: 24px;
    background: #CACACA;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 24px;
    img{
      width: 24px;
      height: 24px;
      border-radius: 50%;
    }
  }
  .del{
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 30px;
    color: white;
    text-align: center;
    background:rgba(130, 130, 130, 0.9);
    display: none;
  }
  &:hover{
    .del{
      display: block;
    }
  }
}
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.module-cover{
  position: absolute;
  height: 70px;
  width: 70px;
  background: #409EFF;
  color: white;
  line-height: 70px;
  text-align: center;
  top: -34px;
  right: 0;
  font-size: 40px;
  border-radius: 5px;
  cursor: pointer;
  .click-block{
    width: 100%;
    position: absolute;
    top:0;
    right: 0;
    background:rgba(130, 130, 130, 0.7);
    line-height: 70px;
    text-align: center;
    color: white;
    font-size: 12px;
    display: none;
    border-radius: 5px;
  }
  &:hover{
    .click-block{
      display: block;
    }
  }
}
.cover-wrapper{
  display: flex;
  flex-wrap: wrap;
  div{
    height: 70px;
    width: 70px;
    background: #409EFF;
    color: white;
    line-height: 70px;
    text-align: center;
    font-size: 40px;
    position: relative;
    border-radius: 5px;
    margin: 5px;
    .click-block{
      width: 100%;
      position: absolute;
      top: -5px;
      left: -5px;
      background:rgba(130, 130, 130, 0.7);
      line-height: 70px;
      text-align: center;
      color: white;
      font-size: 12px;
      display: none;
      cursor: pointer;
      border-radius: 5px;
    }
    &:hover{
      .click-block{
        display: block;
      }
    }
  }

}
.addfilebtn{
  line-height: 22px;
  cursor: pointer;
  color: #909399;
  display: block;
  margin-bottom:5px;
}
.fileitem{
  line-height: 32px;
  margin-bottom: 5px;
  background: #F5F5F5;
  width: 474px;
  padding-left:15px;
  font-size: 12px;
  .uploadtip{
    float:right;
    margin-right: 20px;
    cursor: pointer;
  }
}
</style>